package com.sarracenia.jiangyue.service.impl;

import com.sarracenia.jiangyue.dao.*;
import com.sarracenia.jiangyue.exception.GlobalException;
import com.sarracenia.jiangyue.model.dto.*;
import com.sarracenia.jiangyue.model.dto.result.CodeMessage;
import com.sarracenia.jiangyue.model.entity.*;
import com.sarracenia.jiangyue.model.vo.*;
import com.sarracenia.jiangyue.service.UserService;
import com.sarracenia.jiangyue.utils.EvaluationUtil;
import org.dozer.DozerBeanMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;

/**
 * @author Sarracenia
 * @date 2020/2/11 17:49
 */
/*
    恭喜你看到我写的一坨屎山
 */
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    UserMapper userMapper;
    @Autowired
    PostMapper postMapper;
    @Autowired
    CommentMapper commentMapper;
    @Autowired
    BrowsedPostMapper browsedPostMapper;
    @Autowired
    FriendListMapper friendListMapper;
    @Autowired
    FriendApplicationMapper friendApplicationMapper;
    @Autowired
    UserPostMapper userPostMapper;
    @Autowired
    PostLikedMapper postLikedMapper;
    @Autowired
    ActivityEvaluationMapper activityEvaluationMapper;
    @Autowired
    DozerBeanMapper dozerBeanMapper;
    @Autowired
    BCryptPasswordEncoder bcryptPasswordEncoder;

    //TODO: 密码加密  打算用spring security里面的新加密
    @Override
    public LoginDTO login(LoginVO loginVO) throws GlobalException {
        UserExample userExample = new UserExample();
        userExample.createCriteria().andUsernameEqualTo(loginVO.getUsername());
        List<User> userList = userMapper.selectByExample(userExample);
        if (userList.size() == 0)
            throw new GlobalException(CodeMessage.USER_NOT_EXIST);
        User user = userList.get(0);

        if (!bcryptPasswordEncoder.matches(loginVO.getPassword(), user.getPassword())) {
            throw new GlobalException(CodeMessage.ERROR_USERNAME_PASSWORD);
        }
        user.setIslogin(true);
        userMapper.updateByPrimaryKeySelective(user);
        return new LoginDTO(user.getId(), user.getUsername(), user.getNickname(), user.getDecoration(), user.getAvatorurl(), user.getCreditworthiness());
    }

    @Override
    public EnrollDTO enroll(EnrollVO enrollVO) throws GlobalException {

        UserExample userExample = new UserExample();
        userExample.createCriteria().andUsernameEqualTo(enrollVO.getUsername());
        List<User> userList = userMapper.selectByExample(userExample);
        if (userList.size() != 0)
            throw new GlobalException(CodeMessage.USERNAME_DUPLICATE);


        User userEnroll = dozerBeanMapper.map(enrollVO, User.class);
        userEnroll.setNickname(enrollVO.getUsername());
        //密码加密
        /*
        if(enrollVO.getNickName()==null)
            userEnroll.setNickname("无名氏");
        else{
            userEnroll.setNickname(enrollVO.getNickName());
        }
        if(enrollVO.getIntro()!=null)
            userEnroll.setNickname(enrollVO.getIntro());
         */
        String newPassword = bcryptPasswordEncoder.encode(userEnroll.getPassword());
        userEnroll.setUsername(newPassword);
        //TODO:默认头像
        userEnroll.setAvatorurl("images/ic_avatar_default.png");
        userEnroll.setCreditworthiness(100);
        userEnroll.setIslogin(true);
        userEnroll.setDecoration("  ");
        if (userMapper.insertSelective(userEnroll) == 0)
            throw new GlobalException(CodeMessage.ENROLL_FAIL);
        userList = userMapper.selectByExample(userExample);
        if (userList.size() == 0)
            throw new GlobalException(CodeMessage.ENROLL_FAIL);
        EnrollDTO enrollDTO = new EnrollDTO(userList.get(0).getId());
        return enrollDTO;
    }


    @Override
    public LogoutDTO logout(LogoutVO logoutVO) throws GlobalException {

        User userLogout = userMapper.selectByPrimaryKey(logoutVO.getUserID());
        if (userLogout == null)
            throw new GlobalException(CodeMessage.USER_NOT_EXIST);
        userLogout.setIslogin(false);
        if (userMapper.updateByPrimaryKey(userLogout) == 0)
            throw new GlobalException(CodeMessage.USER_NOT_EXIST);
        return null;
    }

    //获取评论过的post
    @Override
    public List<PostBriefInfoDTO> getCommentedPosts(GetCommentedPostVO getCommentedPostVO) throws GlobalException {

        CommentExample commentExample = new CommentExample();
        commentExample.createCriteria().andCommentUserIdEqualTo(getCommentedPostVO.getUserID());
        List<Comment> commentList = commentMapper.selectByExample(commentExample);
        List<PostBriefInfoDTO> postBriefInfoDTOList = new ArrayList<>();
        //若无评论
        if (commentList.size() == 0)
            return postBriefInfoDTOList;
        HashSet<Integer> postList = new HashSet<>();
        //获取到评论 过滤重复的post
        for (Comment commentTemp : commentList) {
            postList.add(commentTemp.getPostId());
        }

        for (Integer postID : postList) {
            Post postTemp = postMapper.selectByPrimaryKey(postID);
            User author = userMapper.selectByPrimaryKey(postTemp.getUserId());
            PostBriefInfoDTO postBriefInfoDTO = new PostBriefInfoDTO();
            postBriefInfoDTO.setTitle(postTemp.getTitle());
            postBriefInfoDTO.setLastTime(postTemp.getLastTime());
            postBriefInfoDTO.setArticleID(postTemp.getPostId());
            if (author != null)
                postBriefInfoDTO.setAuthor(author.getUsername());
            if (postTemp.getContent().length() >= 30) {
                postBriefInfoDTO.setContent(postTemp.getContent().substring(0, 30));
            } else {
                postBriefInfoDTO.setContent(postTemp.getContent());
            }

            postBriefInfoDTOList.add(postBriefInfoDTO);
        }
        return postBriefInfoDTOList;
    }

    //获取我的信息(评论)
    @Override
    public List<CommentBriefInfoDTO> getCommentMessage(GetMyMessageVO getMyMessageVO) throws GlobalException {

        CommentExample commentExample = new CommentExample();
        commentExample.createCriteria().andCommentedUserIdEqualTo(getMyMessageVO.getUserID());
        List<Comment> commentList = commentMapper.selectByExample(commentExample);

        List<CommentBriefInfoDTO> commentBriefInfoDTOList = new ArrayList<>();

        if (commentList.size() == 0)
            return commentBriefInfoDTOList;

        for (Comment commentTemp : commentList) {
            CommentBriefInfoDTO commentBriefInfoDTO = new CommentBriefInfoDTO();
            commentBriefInfoDTO.setCommentID(commentTemp.getCommentId());
            commentBriefInfoDTO.setContent(commentTemp.getCommentContent());
            User user = userMapper.selectByPrimaryKey(commentTemp.getCommentUserId());
            if (user != null) {
                commentBriefInfoDTO.setAvatorURL(user.getAvatorurl());
                commentBriefInfoDTO.setNickname(user.getNickname());
                commentBriefInfoDTO.setUserID(user.getId());
            }
            commentBriefInfoDTOList.add(commentBriefInfoDTO);
        }
        return commentBriefInfoDTOList;
    }

    //获取浏览过的Post
    @Override
    public List<PostBriefInfoDTO> getBrowsedPosts(GetBrowsedPostVO getBrowsedPostVO) throws GlobalException {

        BrowsedPostExample browsedPostExample = new BrowsedPostExample();
        browsedPostExample.createCriteria().andUserIdEqualTo(getBrowsedPostVO.getUserID());
        List<BrowsedPost> browsedPostList = browsedPostMapper.selectByExample(browsedPostExample);


        List<PostBriefInfoDTO> postBriefInfoDTOList = new ArrayList<>();

        if (browsedPostList.size() == 0)
            return postBriefInfoDTOList;

        for (BrowsedPost browsedPostTemp : browsedPostList) {
            PostBriefInfoDTO postBriefInfoDTO = new PostBriefInfoDTO();
            Post postTemp = postMapper.selectByPrimaryKey(browsedPostTemp.getArticleId());
            User userTemp = userMapper.selectByPrimaryKey(postTemp.getUserId());

            if (postTemp.getContent().length() >= 30) {
                postBriefInfoDTO.setContent(postTemp.getContent().substring(0, 30));
            } else {
                postBriefInfoDTO.setContent(postTemp.getContent());
            }
            if (userTemp != null)
                postBriefInfoDTO.setAuthor(userTemp.getUsername());
            postBriefInfoDTO.setTitle(postTemp.getTitle());
            postBriefInfoDTO.setLastTime(postTemp.getLastTime());
            postBriefInfoDTO.setArticleID(postTemp.getPostId());
            postBriefInfoDTOList.add(postBriefInfoDTO);
        }

        return postBriefInfoDTOList;
    }

    @Override
    public List<PostBriefInfoDTO> getPublishedPosts(GetPublishedPostVO getPublishedPostVO) throws GlobalException {
        PostExample postExample = new PostExample();
        postExample.createCriteria().andUserIdEqualTo(getPublishedPostVO.getUserID());
        List<Post> postList = postMapper.selectByExampleWithBLOBs(postExample);

        List<PostBriefInfoDTO> postBriefInfoDTOList = new ArrayList<>();
        if (postList.size() == 0) {
            return postBriefInfoDTOList;
        }

        for (Post postTemp : postList) {
            PostBriefInfoDTO postBriefInfoDTO = dozerBeanMapper.map(postTemp, PostBriefInfoDTO.class);
            User userTemp = userMapper.selectByPrimaryKey(postTemp.getUserId());
            if (postTemp.getContent().length() >= 31) {
                postBriefInfoDTO.setContent(postTemp.getContent().substring(0, 31));
            } else {
                postBriefInfoDTO.setContent(postTemp.getContent());
            }
            if (userTemp != null)
                postBriefInfoDTO.setAuthor(userTemp.getUsername());
            postBriefInfoDTO.setLastTime(postTemp.getLastTime());
            postBriefInfoDTO.setArticleID(postTemp.getPostId());
            postBriefInfoDTOList.add(postBriefInfoDTO);
        }

        return postBriefInfoDTOList;
    }

    @Override
    public List<PostBriefInfoDTO> getJoinedPosts(GetJoinedPostVO getJoinedPostVO) throws GlobalException {

        UserPostExample userPostExample = new UserPostExample();
        userPostExample.createCriteria().andUserIdEqualTo(getJoinedPostVO.getUserID());
        List<UserPost> userPostList = userPostMapper.selectByExample(userPostExample);
        List<PostBriefInfoDTO> postBriefInfoDTOList = new ArrayList<>();

        if (userPostList.size() == 0) {
            return postBriefInfoDTOList;
        }


        for (UserPost userPostTemp : userPostList) {
            User userTemp = userMapper.selectByPrimaryKey(userPostTemp.getUserId());
            Post postTemp = postMapper.selectByPrimaryKey(userPostTemp.getPostId());
            PostBriefInfoDTO postBriefInfoDTO = new PostBriefInfoDTO();
            postBriefInfoDTO.setTitle(postTemp.getTitle());
            if (postTemp.getContent().length() >= 30) {
                postBriefInfoDTO.setContent(postTemp.getContent().substring(0, 30));
            } else {
                postBriefInfoDTO.setContent(postTemp.getContent());
            }
            User author = userMapper.selectByPrimaryKey(postTemp.getUserId());
            if (author != null && author.getNickname() != null) {
                postBriefInfoDTO.setAuthor(author.getNickname());
            }
            postBriefInfoDTO.setLastTime(postTemp.getLastTime());
            postBriefInfoDTO.setArticleID(postTemp.getPostId());
            postBriefInfoDTOList.add(postBriefInfoDTO);

        }
        return postBriefInfoDTOList;
    }

    @Override
    public List<FriendInfoDTO> searchFriend(SearchFriendVO searchFriendVO) throws GlobalException {

        UserExample userExample = new UserExample();
        userExample.createCriteria().andNicknameLike(searchFriendVO.getAddFriendUserName());
        //List<User> userList=userMapper.selectByExample(userExample);
        List<User> userList = userMapper.selectByKeyWord(searchFriendVO.getAddFriendUserName());

        List<FriendInfoDTO> friendInfoDTOList = new ArrayList<>();
        if (userList.size() == 0)
            return friendInfoDTOList;

        for (User userTemp : userList) {
            if (userTemp.getId() == searchFriendVO.getUserID()) {
                continue;
            }
            FriendInfoDTO friendInfoDTO = dozerBeanMapper.map(userTemp, FriendInfoDTO.class);
            friendInfoDTOList.add(friendInfoDTO);
        }
        return friendInfoDTOList;
    }

    @Override
    public List<GetFriendApplicationDTO> getFriendApplication(GetFriendApplicationVO getFriendApplicationVO) throws GlobalException {

        FriendApplicationExample friendApplicationExample = new FriendApplicationExample();
        friendApplicationExample.createCriteria().andHandledEqualTo(false).andToUseridEqualTo(getFriendApplicationVO.getUserID());
        List<FriendApplication> friendApplicationList = friendApplicationMapper.selectByExample(friendApplicationExample);

        List<GetFriendApplicationDTO> getFriendApplicationDTOList = new ArrayList<>();

        if (friendApplicationList.size() == 0) {
            return getFriendApplicationDTOList;
        }
        for (FriendApplication friendAppTemp : friendApplicationList) {
            GetFriendApplicationDTO getFriendApplicationDTO = new GetFriendApplicationDTO();
            User applicationPoster = userMapper.selectByPrimaryKey(friendAppTemp.getFromUserid());
            if (applicationPoster != null) {
                getFriendApplicationDTO.setAvatorURL(applicationPoster.getAvatorurl());
                getFriendApplicationDTO.setNickname(applicationPoster.getNickname());
                getFriendApplicationDTO.setFriendID(applicationPoster.getId());
            }
            getFriendApplicationDTO.setUserID(friendAppTemp.getToUserid());

            getFriendApplicationDTOList.add(getFriendApplicationDTO);
        }

        return getFriendApplicationDTOList;
    }

    @Override
    public void addFriend(AddFriendVO addFriendVO) throws GlobalException {

        //不可以向自己加好友
        if (addFriendVO.getAddFriendID() == addFriendVO.getUserID()) {
            throw new GlobalException(CodeMessage.ERROR_ADDFRIEND_ID);

        }

        User user = userMapper.selectByPrimaryKey(addFriendVO.getUserID());//好友请求发起者
        if (user == null) {
            throw new GlobalException(CodeMessage.USER_NOT_EXIST);
        }
        User friend = userMapper.selectByPrimaryKey(addFriendVO.getAddFriendID());//好友请求接受者
        if (friend == null) {
            throw new GlobalException(CodeMessage.USER_NOT_EXIST);
        }
        FriendListExample friendListExample = new FriendListExample();
        friendListExample.createCriteria().andUserIdEqualTo(addFriendVO.getUserID()).andFriendIdEqualTo(addFriendVO.getAddFriendID());
        List<FriendList> friendLists = friendListMapper.selectByExample(friendListExample);
        //已经成为好友不能再添加好友
        if (friendLists.size() > 0) {
            throw new GlobalException(CodeMessage.ERROR_ALREADY_FRIEND);
        }

        //不允许重复发送添加好友信息
        FriendApplicationExample friendApplicationExample = new FriendApplicationExample();
        friendApplicationExample.createCriteria().andFromUseridEqualTo(user.getId()).andToUseridEqualTo(friend.getId());
        List<FriendApplication> friendApplicationList = friendApplicationMapper.selectByExample(friendApplicationExample);
        if (friendApplicationList.size() != 0) {
            throw new GlobalException(CodeMessage.ERROR_ALREADY_POST_APPLICATION);
        }

        FriendApplication friendApplication = new FriendApplication();
        friendApplication.setHandled(false);
        friendApplication.setToUserid(friend.getId());
        friendApplication.setFromUserid(user.getId());
        friendApplication.setType(1);
        if (friendApplicationMapper.insertSelective(friendApplication) == 0) {
            throw new GlobalException(CodeMessage.USER_NOT_EXIST);
        }
    }

    @Override
    public void confirmFriendAdd(ConfirmFriendAddVO confirmFriendAddVO) throws GlobalException {
        FriendApplicationExample friendApplicationExample = new FriendApplicationExample();
        friendApplicationExample.createCriteria().andHandledEqualTo(false).andToUseridEqualTo(confirmFriendAddVO.getUserID()).andFromUseridEqualTo(confirmFriendAddVO.getAddFriendID());
        List<FriendApplication> friendApplicationList = friendApplicationMapper.selectByExample(friendApplicationExample);
        FriendApplication friendApplication = friendApplicationList.get(0);
        friendApplication.setHandled(true);
        friendApplicationMapper.updateByPrimaryKey(friendApplication);

        FriendList one = new FriendList();
        one.setUserId(confirmFriendAddVO.getUserID());
        one.setFriendId(confirmFriendAddVO.getAddFriendID());

        FriendList two = new FriendList();
        two.setUserId(confirmFriendAddVO.getAddFriendID());
        two.setFriendId(confirmFriendAddVO.getUserID());

        if (friendListMapper.insertSelective(one) == 0) {
            throw new GlobalException(CodeMessage.FRIEND_APPLICATION_FAIL);
        }
        if (friendListMapper.insertSelective(two) == 0) {
            throw new GlobalException(CodeMessage.FRIEND_APPLICATION_FAIL);
        }
    }

    @Override
    public GetUserInfoDTO getUserInfo(GetUserInfoVO getUserInfoVO) throws GlobalException {
        User user = userMapper.selectByPrimaryKey(getUserInfoVO.getUserID());
        if (user == null)
            throw new GlobalException(CodeMessage.USER_NOT_EXIST);
        GetUserInfoDTO getUserInfoDTO = dozerBeanMapper.map(user, GetUserInfoDTO.class);
        //点赞数+文章
        Integer likeNum = 0;
        PostExample postExample = new PostExample();
        postExample.createCriteria().andUserIdEqualTo(getUserInfoVO.getUserID());
        List<Post> postList = postMapper.selectByExampleWithBLOBs(postExample);
        List<UserArticleInfoDTO> userArticleInfoDTOList = new ArrayList<>();
        for (Post postTemp : postList) {
            likeNum += postTemp.getLikenum();
            UserArticleInfoDTO userArticleInfoDTO = dozerBeanMapper.map(postTemp, UserArticleInfoDTO.class);

            if (postTemp.getContent().length() > 30) {
                userArticleInfoDTO.setContent(postTemp.getContent().substring(0, 30));
            }

            User author = userMapper.selectByPrimaryKey(postTemp.getUserId());

            if (author != null) {
                userArticleInfoDTO.setAuthor(author.getNickname());
            } else {
                userArticleInfoDTO.setAuthor(" ");
            }
            userArticleInfoDTOList.add(userArticleInfoDTO);

        }


        getUserInfoDTO.setLikeNum(likeNum);
        getUserInfoDTO.setArticles(userArticleInfoDTOList);

        return getUserInfoDTO;
    }

    @Override
    public EditUserInfoDTO editUserInfo(EditUserInfoVO editUserInfoVO) throws GlobalException {
        User user = userMapper.selectByPrimaryKey(editUserInfoVO.getUserID());
        if (user == null)
            throw new GlobalException(CodeMessage.USER_NOT_EXIST);
        user.setNickname(editUserInfoVO.getNickname());
        user.setAvatorurl(editUserInfoVO.getAvatorURL());
        user.setDecoration(editUserInfoVO.getDecoration());
        if (userMapper.updateByPrimaryKeySelective(user) == 0)
            throw new GlobalException(CodeMessage.EDIET_USERINFO_FAIL);

        EditUserInfoDTO editUserInfoDTO = dozerBeanMapper.map(user, EditUserInfoDTO.class);
        return editUserInfoDTO;
    }


    @Override
    public GetPostDTO getPostInfo(GetPostVO getPostVO) throws GlobalException {

        Post postGet = postMapper.selectByPrimaryKey(getPostVO.getArticleID());
        if (postGet == null)
            throw new GlobalException(CodeMessage.POST_NOT_EXIST);
        if (getPostVO.getUserID() != null) {
            User userValid = userMapper.selectByPrimaryKey(getPostVO.getUserID());
            if (userValid == null)
                throw new GlobalException(CodeMessage.USER_NOT_EXIST);
        }

        GetPostDTO getPostDTO = new GetPostDTO();
        PostInfoDTO postInfoDTO = dozerBeanMapper.map(postGet, PostInfoDTO.class);
        if (userMapper.selectByPrimaryKey(postGet.getUserId()) != null)
            postInfoDTO.setAvatorURL(userMapper.selectByPrimaryKey(postGet.getUserId()).getAvatorurl());
        postInfoDTO.setDecoration(userMapper.selectByPrimaryKey(postGet.getUserId()).getDecoration());
        postInfoDTO.setAuthorID(userMapper.selectByPrimaryKey(postGet.getUserId()).getId());
        if (getPostVO.getUserID() == null) {
            postInfoDTO.setLike(false);
        } else {
            //是否喜欢
            PostLikedExample postLikedExample = new PostLikedExample();
            postLikedExample.createCriteria().andArticleIdEqualTo(getPostVO.getArticleID()).andUserIdEqualTo(getPostVO.getUserID());
            List<PostLiked> postLikeds = postLikedMapper.selectByExample(postLikedExample);
            if (postLikeds.size() == 0)
                postInfoDTO.setLike(false);
            else {
                postInfoDTO.setLike(true);
            }
        }
        //joinnum
        UserPostExample userPostExample = new UserPostExample();
        userPostExample.createCriteria().andPostIdEqualTo(getPostVO.getArticleID());
        List<UserPost> userPostList = userPostMapper.selectByExample(userPostExample);
        postInfoDTO.setJoinNum(userPostList.size());

        //是否加入
        if (getPostVO.getUserID() == null) {
            postInfoDTO.setJoin(false);
        } else {
            userPostExample.clear();
            userPostExample.createCriteria().andPostIdEqualTo(getPostVO.getArticleID()).andUserIdEqualTo(getPostVO.getUserID());
            List<UserPost> userPostList2 = userPostMapper.selectByExample(userPostExample);
            if (userPostList2.size() == 0) {
                postInfoDTO.setJoin(false);
            } else {
                postInfoDTO.setJoin(true);
            }
        }
        getPostDTO.setArticle(postInfoDTO);
        //评论
        List<CommentInfoDTO> commentInfoDTOList = new ArrayList<>();

        CommentExample commentExample = new CommentExample();
        commentExample.createCriteria().andPostIdEqualTo(getPostVO.getArticleID());
        List<Comment> commentList = commentMapper.selectByExample(commentExample);
        if (commentList.size() == 0) {
            getPostDTO.setComment(commentInfoDTOList);
            return getPostDTO;
        }

        for (Comment commentTemp : commentList) {
            CommentInfoDTO commentInfoDTO = new CommentInfoDTO();
            commentInfoDTO.setContent(commentTemp.getCommentContent());
            commentInfoDTO.setId(commentTemp.getCommentId());

            User author = userMapper.selectByPrimaryKey(commentTemp.getCommentUserId());
            if (author != null) {
                commentInfoDTO.setAuthorID(author.getId());
                commentInfoDTO.setAuthor(author.getNickname());
                commentInfoDTO.setAvatorURL(author.getAvatorurl());
                commentInfoDTO.setDecoration(author.getDecoration());
            }
            commentInfoDTOList.add(commentInfoDTO);
        }
        getPostDTO.setComment(commentInfoDTOList);

        if (getPostVO.getUserID() != null) {
            BrowsedPostExample browsedPostExample = new BrowsedPostExample();
            browsedPostExample.createCriteria().andUserIdEqualTo(getPostVO.getUserID()).andArticleIdEqualTo(getPostVO.getArticleID());
            List<BrowsedPost> browsedPostList = browsedPostMapper.selectByExample(browsedPostExample);
            if (browsedPostList.size() == 0) {
                BrowsedPost browsedPost = new BrowsedPost();
                browsedPost.setUserId(getPostVO.getUserID());
                browsedPost.setArticleId(getPostVO.getArticleID());
                browsedPostMapper.insertSelective(browsedPost);
            }
        }
        return getPostDTO;
    }

    @Override
    public PostHomeListDTO getPostList(GetPostListVO getPostListVO) throws GlobalException {
        PostExample postExample = new PostExample();
        postExample.createCriteria().andUserIdIsNotNull();
        List<Post> postList = postMapper.selectByExampleWithBLOBs(postExample);
        PostHomeListDTO postHomeListDTO = new PostHomeListDTO();

        if (getPostListVO.getUserID() != null) {

            User userTest = userMapper.selectByPrimaryKey(getPostListVO.getUserID());
            if (userTest == null)
                throw new GlobalException(CodeMessage.USER_NOT_EXIST);
        }


        if (postList.size() == 0) {
            return postHomeListDTO;
        }
        List<PostHomeDTO> postHomeDTOList = new ArrayList<>();
        for (Post postTemp : postList) {

            PostHomeDTO postHomeDTO = dozerBeanMapper.map(postTemp, PostHomeDTO.class);
            if (postTemp.getContent().length() >= 30) {
                postHomeDTO.setContent(postTemp.getContent().substring(0, 30));
            } else {
                postHomeDTO.setContent(postTemp.getContent());
            }
            User author = userMapper.selectByPrimaryKey(postTemp.getUserId());
            if (author != null) {
                postHomeDTO.setAuthor(author.getNickname());

                if (getPostListVO.getUserID() == null) {
                    postHomeDTO.setLike(false);
                } else {
                    PostLikedExample postLikedExample = new PostLikedExample();
                    postLikedExample.createCriteria()
                            .andArticleIdEqualTo(postTemp.getPostId())
                            .andUserIdEqualTo(getPostListVO.getUserID());
                    List<PostLiked> postLikeds = postLikedMapper.selectByExample(postLikedExample);
                    if (postLikeds.size() == 0) {
                        postHomeDTO.setLike(false);
                    } else {
                        postHomeDTO.setLike(true);
                    }
                }
            } else {
                postHomeDTO.setLike(false);
            }
            postHomeDTOList.add(postHomeDTO);
        }
        postHomeListDTO.setData(postHomeDTOList);

        return postHomeListDTO;
    }

    @Override
    public AddPostDTO addPost(AddPostVO addPostVO) throws GlobalException {
        User user = userMapper.selectByPrimaryKey(addPostVO.getUserID());
        if (user == null)
            throw new GlobalException(CodeMessage.USER_NOT_EXIST);
        Post postAdd = dozerBeanMapper.map(addPostVO, Post.class);
        Date ArticalAddDate = new Date();
        postAdd.setFirstTime(ArticalAddDate);
        postAdd.setCommentNum(0);
        postAdd.setLikenum(0);
        if (postMapper.insertSelective(postAdd) == 0) {
            throw new GlobalException(CodeMessage.INTERNAL_SERVER_ERROR);
        }
        return null;
    }

    @Override
    public DeletePostDTO deletePost(DeletePostVO deletePostVO) throws GlobalException {

        Post postDelete = postMapper.selectByPrimaryKey(deletePostVO.getPostID());
        if (postDelete == null) {
            throw new GlobalException(CodeMessage.POST_NOT_EXIST);
        }
        if (postDelete.getUserId() != deletePostVO.getUserID()) {
            throw new GlobalException(CodeMessage.BLOG_NOT_AUTHENTICATED);
        }
        postMapper.deleteByPrimaryKey(deletePostVO.getPostID());
        return null;
    }

    @Override
    public LikePostDTO likePost(LikePostVO likePostVO) throws GlobalException {


        if (likePostVO.isLike()) {
            //在点赞/喜欢状态下
            //要取消点赞/喜欢
            PostLikedExample postLikedExample = new PostLikedExample();
            postLikedExample.createCriteria().andArticleIdEqualTo(likePostVO.getArticleID()).andUserIdEqualTo(likePostVO.getUserID());
            List<PostLiked> postLikedList = postLikedMapper.selectByExample(postLikedExample);
            if (postLikedList.size() == 0) {
                System.out.println(1);
                //在喜欢帖子状态下 like中查不到
                throw new GlobalException(CodeMessage.ERROR_LIKE_STATUS);
            }
            Post post = postMapper.selectByPrimaryKey(likePostVO.getArticleID());
            if (post == null) {
                throw new GlobalException(CodeMessage.POST_NOT_EXIST);
            }
            PostLiked postLiked = postLikedList.get(0);
            Integer likeNum = post.getLikenum();
            likeNum--;
            post.setLikenum(likeNum);
            postMapper.updateByPrimaryKey(post);
            postLikedMapper.deleteByPrimaryKey(postLiked.getId());

        } else {
            //不喜欢状态下
            //要点赞/喜欢
            PostLikedExample postLikedExample = new PostLikedExample();
            postLikedExample.createCriteria().andArticleIdEqualTo(likePostVO.getArticleID()).andUserIdEqualTo(likePostVO.getUserID());
            List<PostLiked> postLikedList = postLikedMapper.selectByExample(postLikedExample);
            if (postLikedList.size() != 0) {
                //在非喜欢帖子状态下 like中查到了
                System.out.println(2);
                throw new GlobalException(CodeMessage.ERROR_LIKE_STATUS);
            }
            Post post = postMapper.selectByPrimaryKey(likePostVO.getArticleID());
            if (post == null) {
                throw new GlobalException(CodeMessage.POST_NOT_EXIST);
            }
            PostLiked postLiked = new PostLiked();
            postLiked.setArticleId(likePostVO.getArticleID());
            postLiked.setUserId(likePostVO.getUserID());
            Integer likeNum = post.getLikenum();
            if (likeNum >= 0)
                likeNum++;
            post.setLikenum(likeNum);
            postMapper.updateByPrimaryKey(post);
            postLikedMapper.insertSelective(postLiked);
        }
        LikePostDTO likePostDTO = new LikePostDTO();
        likePostDTO.setLike(!likePostVO.isLike());
        return likePostDTO;
    }

    @Override
    public JoinActivityDTO joinPost(JoinActivityVO joinActivityVO) throws GlobalException {

        Date now = new Date();
        //检查活动是否过期和人数是否已经达上限

        Post postJoined = postMapper.selectByPrimaryKey(joinActivityVO.getArticleID());
        //若活动不存在
        if (postJoined == null) {
            throw new GlobalException(CodeMessage.POST_NOT_EXIST);
        }
        //若活动已经过期
        if (postJoined.getLastTime().getTime() < now.getTime()) {
            throw new GlobalException(CodeMessage.ERROR_JOINED_OVERDUE);
        }
        UserPostExample userPostExample2 = new UserPostExample();
        userPostExample2.createCriteria()
                .andPostIdEqualTo(joinActivityVO.getArticleID());
        List<UserPost> userPostListNum = userPostMapper.selectByExample(userPostExample2);
        //若活动人数超出上限
        if (postJoined.getLimitJoinNum() <= userPostListNum.size()) {
            throw new GlobalException(CodeMessage.ERROR_JOINED_MAX);
        }

        //检查是否重复加入

        UserPostExample userPostExample = new UserPostExample();
        userPostExample.createCriteria()
                .andPostIdEqualTo(joinActivityVO.getArticleID())
                .andUserIdEqualTo(joinActivityVO.getUserID());
        List<UserPost> userPostList = userPostMapper.selectByExample(userPostExample);
        //若重复添加抛出异常
        if (userPostList.size() != 0) {
            throw new GlobalException(CodeMessage.JOIN_ACTIVITY_FAIL);
        }

        UserPost userPost = new UserPost();
        userPost.setPostId(joinActivityVO.getArticleID());
        userPost.setUserId(joinActivityVO.getUserID());
        if (userPostMapper.insertSelective(userPost) == 0) {
            throw new GlobalException(CodeMessage.JOIN_ACTIVITY_FAIL);
        }
        return new JoinActivityDTO(userPostListNum.size() + 1);
    }

    @Override
    public AddCommentDTO addComment(AddCommentVO addCommentVO) throws GlobalException {

        User user = userMapper.selectByPrimaryKey(addCommentVO.getUserID());
        if (user == null)
            throw new GlobalException(CodeMessage.USER_NOT_EXIST);

        Comment commentAdd = dozerBeanMapper.map(addCommentVO, Comment.class);
        Post postCommented = postMapper.selectByPrimaryKey(addCommentVO.getArticleID());
        if (postCommented == null) {
            throw new GlobalException(CodeMessage.POST_NOT_EXIST);
        }
        Integer commenNum = postCommented.getCommentNum() + 1;
        postCommented.setCommentNum(commenNum);
        commentAdd.setCommentedUserId(postCommented.getUserId());
        commentAdd.setCommentUserId(addCommentVO.getUserID());
        if (commentMapper.insertSelective(commentAdd) == 0) {
            throw new GlobalException(CodeMessage.BLOG_POST_COMMENT_ERROR);
        }
        postMapper.updateByPrimaryKeyWithBLOBs(postCommented);
        return null;
    }

    @Override
    public EvaluateActivityDTO evaluateActivity(EvaluateActivityVO evaluateActivityVO) throws GlobalException {
        User evaluator = userMapper.selectByPrimaryKey(evaluateActivityVO.getUserID());
        if (evaluator == null) {
            throw new GlobalException(CodeMessage.USER_NOT_EXIST);
        }
        Post postEvaluated = postMapper.selectByPrimaryKey(evaluateActivityVO.getArticleID());
        if (postEvaluated == null) {
            throw new GlobalException(CodeMessage.POST_NOT_EXIST);
        }
        //判断是否参加
        UserPostExample userPostExample = new UserPostExample();
        userPostExample.createCriteria()
                .andPostIdEqualTo(evaluateActivityVO.getArticleID())
                .andUserIdEqualTo(evaluateActivityVO.getUserID());
        System.out.println("post" + evaluateActivityVO.getArticleID());
        System.out.println("user" + evaluateActivityVO.getUserID());
        List<UserPost> userPostList = userPostMapper.selectByExample(userPostExample);
        //没参加不给评价
        if (userPostList.size() == 0) {
            throw new GlobalException(CodeMessage.ERROR_EVALUATE_NEED_JOIN);
        }

        //不准重复评价
        ActivityEvaluationExample activityEvaluationExample = new ActivityEvaluationExample();
        activityEvaluationExample.createCriteria().andUserIdEqualTo(evaluateActivityVO.getUserID()).andPostIdEqualTo(evaluateActivityVO.getArticleID());
        List<ActivityEvaluation> activityEvaluationList = activityEvaluationMapper.selectByExample(activityEvaluationExample);
        if (activityEvaluationList.size() != 0) {
            throw new GlobalException(CodeMessage.ERROR_ALREADY_EVALUATED);
        }

        if (postEvaluated.getEvaluate() == null) {
            postEvaluated.setEvaluate(evaluateActivityVO.getTotalEvaluate());
        } else {
            Integer PostEvaluationNum = postEvaluated.getEvaluate();
            PostEvaluationNum += evaluateActivityVO.getTotalEvaluate();
            PostEvaluationNum /= 2;
            postEvaluated.setEvaluate(PostEvaluationNum);
        }

        for (UserEvaluateVO userEvaluateVO : evaluateActivityVO.getEvaluate()) {
            User userTemp = userMapper.selectByPrimaryKey(userEvaluateVO.getUserID());
            if (userTemp == null) {
                //throw new GlobalException(CodeMessage.USER_NOT_EXIST);
                //暂且写成这样，一个错误不会影响其他的人的写入
                continue;
            }
            Integer creditWorthiness = userTemp.getCreditworthiness();
            //使用Util写好的规则
            creditWorthiness += EvaluationUtil.changeCreditWorthiness(userEvaluateVO.getData());
            userTemp.setCreditworthiness(creditWorthiness);
            userMapper.updateByPrimaryKey(userTemp);

        }

        ActivityEvaluation activityEvaluation = new ActivityEvaluation();
        activityEvaluation.setPostId(evaluateActivityVO.getArticleID());
        activityEvaluation.setUserId(evaluateActivityVO.getUserID());
        activityEvaluation.setGrade(evaluateActivityVO.getTotalEvaluate());
        activityEvaluationMapper.insertSelective(activityEvaluation);

        //更新post得分
        postMapper.updateByPrimaryKey(postEvaluated);
        return null;
    }

    @Override
    public List<GetEvaluateUserDTO> getEvaluateUserList(GetEvaluateUserListVO getEvaluateUserListVO) throws GlobalException {

        UserPostExample userPostExample = new UserPostExample();
        userPostExample.createCriteria().andPostIdEqualTo(getEvaluateUserListVO.getArticleID()).andUserIdNotEqualTo(getEvaluateUserListVO.getUserID());
        List<UserPost> userPostList = userPostMapper.selectByExample(userPostExample);
        List<GetEvaluateUserDTO> getEvaluateUserDTOList = new ArrayList<>();
        if (userPostList.size() == 0) {
            return getEvaluateUserDTOList;
        }
        for (UserPost userPost : userPostList) {

            User userTemp = userMapper.selectByPrimaryKey(userPost.getId());
            if (userTemp != null) {
                GetEvaluateUserDTO getEvaluateUserDTO = dozerBeanMapper.map(userTemp, GetEvaluateUserDTO.class);
                getEvaluateUserDTOList.add(getEvaluateUserDTO);
            }

        }


        return getEvaluateUserDTOList;
    }


    @Override
    public List<FriendInfoDTO> getFriendList(GetFriendListVO getFriendListVO) throws GlobalException {
        User user = userMapper.selectByPrimaryKey(getFriendListVO.getUserID());
        //用户不存在
        if (user == null) {
            throw new GlobalException(CodeMessage.USER_NOT_EXIST);
        }

        List<FriendInfoDTO> friendInfoDTOList = new ArrayList<>();
        //查找朋友
        FriendListExample friendListExample = new FriendListExample();
        friendListExample.createCriteria().andUserIdEqualTo(getFriendListVO.getUserID());
        List<FriendList> friendLists = friendListMapper.selectByExample(friendListExample);

        if (friendLists.size() == 0) {
            return friendInfoDTOList;
        }
        for (FriendList friendListTemp : friendLists) {
            User friendTemp = userMapper.selectByPrimaryKey(friendListTemp.getFriendId());
            //用户不存在
            if (friendTemp == null) {
                //throw new GlobalException(CodeMessage.USER_NOT_EXIST);
                continue;
            }
            FriendInfoDTO friendInfoDTO = dozerBeanMapper.map(friendTemp, FriendInfoDTO.class);
            friendInfoDTOList.add(friendInfoDTO);
        }
        return friendInfoDTOList;
    }
}
